package com.why.simpleboot.core.server.netty.handler;

import com.why.simpleboot.core.core.entity.MethodDefinition;
import com.why.simpleboot.core.server.netty.resolver.ParameterResolver;
import com.why.simpleboot.core.server.netty.resolver.ParameterResolverFactory;
import com.why.simpleboot.core.server.netty.response.SimpleResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Parameter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * @program: why-simpleboot-framework
 * @description:
 * @author: @why
 * @create: 2021-05-22 14:32
 **/
public class PostRequestHandler extends AbstractRequestHandler {
    private Logger log = LoggerFactory.getLogger(PostRequestHandler.class);

    public PostRequestHandler() {

    }

    @Override
    public FullHttpResponse handle(FullHttpRequest httpRequest) {
        RequestHandler handler = canProcessCurrentRequest(httpRequest, HttpMethod.POST);
        if (handler == null) {
            return SimpleResponse.createError(httpRequest.uri(), "无法处理该请求", HttpResponseStatus.NOT_FOUND);
        }
        if (!handler.equals(this)) {
            return handler.handle(httpRequest);
        }
//        if (!GeneralUtlis.isAvailableContentType(httpRequest.headers(), HttpHeaderValues.APPLICATION_JSON)) {
//            return SimpleResponse.createError(super.requestParamDecoder.uri(), "无法处理非json请求~", HttpResponseStatus.BAD_REQUEST);
//        }

        MethodDefinition methodDefinition = getMethodDefinition(httpRequest);
        if (methodDefinition == null) {
            return SimpleResponse.createError(super.requestParamDecoder.uri(),
                    "无法处理该请求url,请确定url地址是否正确~", HttpResponseStatus.NOT_FOUND);
        }

        String json = httpRequest.content().toString(StandardCharsets.UTF_8);
        methodDefinition.setJson(json);
        Parameter[] parameters = methodDefinition.getMethod().getParameters();
        ArrayList<Object> args = new ArrayList<>();


//        完成参数的处理
        for (Parameter parameter : parameters) {
            ParameterResolver resolver = ParameterResolverFactory.getResolver(parameter);
            if (resolver == null) {
                log.error("无解析器发现。");
                throw new RuntimeException("没有找到解析器。。");
            }
            Object arg = resolver.resolve(methodDefinition, parameter);
            args.add(arg);
        }

        Object result = invokeMethodForTarget(methodDefinition, args.toArray());
        return SimpleResponse.createOk(result);
    }

}
